import React from "react";
import { Renderer, Common } from "@k8slens/extensions";

type KubeEvent = Renderer.K8sApi.KubeEvent;

const {
  Component: { MenuItem, Icon },
} = Renderer;
const { Util } = Common;
//窗口开关状态
import { eventsLLMExplainDialogState } from "../dialog/events-llm-explain-dialog";

import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import { llmPreferenceStore } from "../../llm/preference/llm-preference-store";
import { getStream } from "../../llm/model/llm-model";
export class EventsLLMExplainMenu extends React.Component<
  Renderer.Component.KubeObjectMenuProps<KubeEvent>
> {
  async explainEventByLLMFirst(e: KubeEvent) {
    if (!llmPreferenceStore.apiKey || llmPreferenceStore.apiKey.trim() == "") {
      alert("Please set your api key in LLM Preference");
      return;
    }
    if (!llmPreferenceStore.model || llmPreferenceStore.model.trim() == "") {
      alert("Please set your model in LLM Preference");
      return;
    }
    if (
      !llmPreferenceStore.baseURL ||
      llmPreferenceStore.baseURL.trim() == ""
    ) {
      alert("Please set your baseURL in LLM Preference");
      return;
    }
    eventsLLMExplainDialogState.isOpen.set(true);

    const messages = [
      new SystemMessage(llmPreferenceStore.roleDesc),
      llmPreferenceStore.useK8sTool?new HumanMessage("k8s event: " + JSON.stringify(e)+",先获取异常pod的信息和日志再分析"):new HumanMessage("k8s event: " + JSON.stringify(e)),
    ];
    eventsLLMExplainDialogState.history.replace(messages);

    eventsLLMExplainDialogState.answer.set("");

    eventsLLMExplainDialogState.answers.replace([]);

    eventsLLMExplainDialogState.step.set(0);

    eventsLLMExplainDialogState.isLoading.set(true);
    try {
      const stream = await getStream(messages);
      const chunks: string[] = [];
      for await (const chunk of stream) {
        if(!eventsLLMExplainDialogState.isOpen.get()){//窗口关闭后停止
          break ;
        }
        if (Array.isArray(chunk)) {
          for (const c of chunk) {
            if (c.content && !c.tool_call_id) {
              chunks.push(c.content.toString());
              eventsLLMExplainDialogState.answer.set(chunks.join(""));
            }
          }
        } else {
          if (chunk.content && !chunk.tool_call_id) {
            chunks.push(chunk.content.toString());
            eventsLLMExplainDialogState.answer.set(chunks.join(""));
          }
        }
      }

      eventsLLMExplainDialogState.step.set(1);
      eventsLLMExplainDialogState.history.push(
        new SystemMessage(chunks.join(""))
      );
      eventsLLMExplainDialogState.answers.push(chunks.join(""));
    } catch (err) {
      console.log(err);
      alert(err);
    }
    eventsLLMExplainDialogState.isLoading.set(false);
  }
  render() {
    const { object, toolbar } = this.props;

    return (
      <MenuItem
        onClick={Util.prevDefault(async () => {
          await this.explainEventByLLMFirst(object);
        })}
      >
        <Icon
          material="pageview"
          interactive={toolbar}
          tooltip={toolbar && "LLM Explain"}
        />
        <span className="title">LLM Explain</span>
      </MenuItem>
    );
  }
}
